import { reqCartList, reqDeleteCart, reqCheckCart } from '@/api'
// home模块的小仓库
// state：仓库存储数据的地方
const state = {
    CartList: []
}
// mutations:修改state的唯一手段
const mutations = {
    CartList(state, val) {
        state.CartList = val
    }

}
// actions：处理action，可以书写自己的业务逻辑，也可以处理异步
const actions = {
    async CartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit('CartList', result.data)
        }
    },
    async DeleteCart({ commit }, skuId) {
        let result = await reqDeleteCart(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async CheckCart({ commit }, { skuId, isChecked }) {
        let result = await reqCheckCart(skuId, isChecked)
        console.log(result)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // deleteAllCheckCart(context){
    // context:小仓库
    deleteAllCheckCart({ dispatch, getters }) {
        // console.log(context)
        let PromiseAll = []
        console.log(getters)
        getters.CartList.cartInfoList.forEach((item) => {
            let promise = item.isChecked == 1 ? dispatch('DeleteCart', item.skuId) : ''
            PromiseAll.push(promise)
        })
        // 判断数组中是否全为promise
        return Promise.all(PromiseAll)
    },
    updateisAllCheck({ dispatch, state }, isChecked) {
        let PromiseAll = []
        state.CartList[0].cartInfoList.forEach((item) => {

            let promise = dispatch('CheckCart', { skuId: item.skuId, isChecked })
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)


    }

}
// getters:理解为计算属性，用于简化仓库数据，让组件获取仓库的数据更加方便
const getters = {
    CartList(state) {
        return state.CartList[0] || {}
    },

}
export default ({
    state,
    mutations,
    actions,
    getters
})